"""
订阅管理路由
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional
import time

from ..models import (
    SubscriptionsListResponse, SubscriptionResponse, SubscriptionRequest,
    BaseResponse, ErrorResponse
)
from ..storage import data_manager, SubscriptionRecord
from ..logger import logger
from ..utils import generate_id

router = APIRouter()


@router.get("/subscriptions", response_model=SubscriptionsListResponse)
async def get_subscriptions(
    client_id: Optional[str] = Query(None, description="客户端ID过滤"),
    server_id: Optional[str] = Query(None, description="服务器ID过滤"),
    status: Optional[str] = Query(None, description="状态过滤"),
    model_name: Optional[str] = Query(None, description="模型名称过滤")
):
    """获取订阅列表"""
    try:
        # 从存储获取所有订阅
        subscriptions = await data_manager.get_subscriptions()
        
        # 应用过滤器
        filtered_subscriptions = subscriptions
        
        if client_id:
            filtered_subscriptions = [s for s in filtered_subscriptions if s.client_id == client_id]
            
        if server_id:
            filtered_subscriptions = [s for s in filtered_subscriptions if s.server_id == server_id]
            
        if status:
            filtered_subscriptions = [s for s in filtered_subscriptions if s.status == status]
            
        if model_name:
            filtered_subscriptions = [s for s in filtered_subscriptions if s.model_name == model_name]
        
        # 转换为响应模型
        subscription_responses = [
            SubscriptionResponse(
                id=sub.id,
                client_id=sub.client_id,
                client_name=sub.client_name,
                model_name=sub.model_name,
                model_version=sub.model_version,
                server_id=sub.server_id,
                subscribed_at=sub.subscribed_at,
                last_checked=sub.last_checked,
                status=sub.status,
                auto_update=sub.auto_update,
                notification_channels=sub.notification_channels,
                callback_url=sub.callback_url
            )
            for sub in filtered_subscriptions
        ]
        
        return SubscriptionsListResponse(
            subscriptions=subscription_responses,
            total=len(subscription_responses),
            message=f"Found {len(subscription_responses)} subscriptions"
        )
        
    except Exception as e:
        logger.error(f"Failed to get subscriptions: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve subscriptions")


@router.get("/subscriptions/{subscription_id}", response_model=SubscriptionResponse)
async def get_subscription(subscription_id: str):
    """获取指定订阅详情"""
    try:
        subscription = await data_manager.get_subscription_by_id(subscription_id)
        
        if not subscription:
            raise HTTPException(status_code=404, detail="Subscription not found")
        
        return SubscriptionResponse(
            id=subscription.id,
            client_id=subscription.client_id,
            client_name=subscription.client_name,
            model_name=subscription.model_name,
            model_version=subscription.model_version,
            server_id=subscription.server_id,
            subscribed_at=subscription.subscribed_at,
            last_checked=subscription.last_checked,
            status=subscription.status,
            auto_update=subscription.auto_update,
            notification_channels=subscription.notification_channels,
            callback_url=subscription.callback_url
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get subscription {subscription_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve subscription")


@router.post("/subscriptions", response_model=BaseResponse)
async def create_subscription(subscription_request: SubscriptionRequest):
    """创建新订阅"""
    try:
        # 验证服务器是否存在
        server = await data_manager.get_server_by_id(subscription_request.server_id)
        if not server:
            raise HTTPException(status_code=404, detail="Server not found")
        
        # 检查是否已存在相同的订阅
        existing_subscriptions = await data_manager.get_subscriptions()
        for existing_sub in existing_subscriptions:
            if (existing_sub.client_id == subscription_request.client_id and
                existing_sub.model_name == subscription_request.model_name and
                existing_sub.server_id == subscription_request.server_id and
                existing_sub.status == "active"):
                raise HTTPException(
                    status_code=409, 
                    detail="Active subscription already exists for this client, model, and server"
                )
        
        # 创建新订阅
        current_time = time.time()
        new_subscription = SubscriptionRecord(
            id=generate_id(),
            client_id=subscription_request.client_id,
            client_name=subscription_request.client_name,
            model_name=subscription_request.model_name,
            model_version=subscription_request.model_version,
            server_id=subscription_request.server_id,
            subscribed_at=current_time,
            last_checked=current_time,
            status="active",
            auto_update=subscription_request.auto_update,
            notification_channels=subscription_request.notification_channels,
            callback_url=subscription_request.callback_url
        )
        
        # 保存到存储
        await data_manager.add_subscription(new_subscription)
        
        logger.info(f"Created subscription: {new_subscription.client_name} -> {new_subscription.model_name}")
        
        return BaseResponse(
            message=f"Subscription created successfully for {new_subscription.model_name}"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to create subscription: {e}")
        raise HTTPException(status_code=500, detail="Failed to create subscription")


@router.put("/subscriptions/{subscription_id}/status", response_model=BaseResponse)
async def update_subscription_status(subscription_id: str, status: str):
    """更新订阅状态"""
    try:
        # 验证状态值
        valid_statuses = ["active", "paused", "cancelled"]
        if status not in valid_statuses:
            raise HTTPException(
                status_code=400, 
                detail=f"Invalid status. Must be one of: {', '.join(valid_statuses)}"
            )
        
        # 获取订阅
        subscription = await data_manager.get_subscription_by_id(subscription_id)
        if not subscription:
            raise HTTPException(status_code=404, detail="Subscription not found")
        
        # 更新状态
        old_status = subscription.status
        subscription.status = status
        subscription.last_checked = time.time()
        
        # 保存更新
        await data_manager.update_subscription(subscription)
        
        logger.info(f"Updated subscription {subscription_id} status: {old_status} -> {status}")
        
        return BaseResponse(
            message=f"Subscription status updated to {status}"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to update subscription {subscription_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to update subscription")


@router.delete("/subscriptions/{subscription_id}", response_model=BaseResponse)
async def delete_subscription(subscription_id: str):
    """删除订阅"""
    try:
        # 检查订阅是否存在
        subscription = await data_manager.get_subscription_by_id(subscription_id)
        if not subscription:
            raise HTTPException(status_code=404, detail="Subscription not found")
        
        # 删除订阅
        await data_manager.delete_subscription(subscription_id)
        
        logger.info(f"Deleted subscription: {subscription.client_name} -> {subscription.model_name}")
        
        return BaseResponse(
            message=f"Subscription for {subscription.model_name} deleted successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to delete subscription {subscription_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete subscription")


@router.post("/subscriptions/{subscription_id}/check", response_model=BaseResponse)
async def check_subscription(subscription_id: str):
    """手动检查订阅的模型更新"""
    try:
        # 获取订阅
        subscription = await data_manager.get_subscription_by_id(subscription_id)
        if not subscription:
            raise HTTPException(status_code=404, detail="Subscription not found")
        
        if subscription.status != "active":
            raise HTTPException(status_code=400, detail="Subscription is not active")
        
        # 获取服务器信息
        server = await data_manager.get_server_by_id(subscription.server_id)
        if not server:
            raise HTTPException(status_code=404, detail="Server not found")
        
        # TODO: 实现实际的模型检查逻辑
        # 这里应该向服务器查询模型更新
        
        # 更新检查时间
        subscription.last_checked = time.time()
        await data_manager.update_subscription(subscription)
        
        logger.info(f"Checked subscription: {subscription.client_name} -> {subscription.model_name}")
        
        return BaseResponse(
            message=f"Subscription check completed for {subscription.model_name}"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to check subscription {subscription_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to check subscription")


@router.get("/subscriptions/client/{client_id}", response_model=SubscriptionsListResponse)
async def get_client_subscriptions(client_id: str):
    """获取指定客户端的所有订阅"""
    try:
        # 获取客户端的所有订阅
        all_subscriptions = await data_manager.get_subscriptions()
        client_subscriptions = [
            sub for sub in all_subscriptions 
            if sub.client_id == client_id
        ]
        
        # 转换为响应模型
        subscription_responses = [
            SubscriptionResponse(
                id=sub.id,
                client_id=sub.client_id,
                client_name=sub.client_name,
                model_name=sub.model_name,
                model_version=sub.model_version,
                server_id=sub.server_id,
                subscribed_at=sub.subscribed_at,
                last_checked=sub.last_checked,
                status=sub.status,
                auto_update=sub.auto_update,
                notification_channels=sub.notification_channels,
                callback_url=sub.callback_url
            )
            for sub in client_subscriptions
        ]
        
        return SubscriptionsListResponse(
            subscriptions=subscription_responses,
            total=len(subscription_responses),
            message=f"Found {len(subscription_responses)} subscriptions for client {client_id}"
        )
        
    except Exception as e:
        logger.error(f"Failed to get client subscriptions: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve client subscriptions")
